package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.PathUtils;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FindFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FindFragment extends Fragment {

    private ListView mListView;
    private SimpleAdapter mAdapter;
    private List<Map<String, Object>> mList;
    private int images[] = {R.mipmap.car_friend, R.mipmap.move_help, R.mipmap.car_news};
    private String titles[] = {"车友圈", "挪车助手", "汽车资讯"};
    private String descs[] = {"看看车友都在干什么", "一键呼叫，烦恼解决", "最新的新闻资讯"};
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private FragmentManager manager;
    private FragmentTransaction mTransaction;

    private OnFragmentInteractionListener mListener;
    private TextView tv_gas_address;
    private TextView tv_gas_90_price;
    private TextView tv_gas_93_price;
    private TextView tv_gas_97_price;
    private TextView tv_gas_0_price;
    private RequestQueue queue;
    private TextView tv_gas_type_90;
    private TextView tv_gas_type_93;
    private TextView tv_gas_type_97;
    private TextView tv_gas_type_0;

    public FindFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FindFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FindFragment newInstance(String param1, String param2) {
        FindFragment fragment = new FindFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        initView(view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        manager = getActivity().getSupportFragmentManager();

    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_find_menu);


        tv_gas_address = (TextView) view.findViewById(R.id.tv_gas_address);   //地点 地址
        tv_gas_90_price = (TextView) view.findViewById(R.id.tv_gas_90_price);
        tv_gas_93_price = (TextView) view.findViewById(R.id.tv_gas_93_price);
        tv_gas_97_price = (TextView) view.findViewById(R.id.tv_gas_97_price);
        tv_gas_0_price = (TextView) view.findViewById(R.id.tv_gas_0_price);
        initData();
        tv_gas_type_90 = (TextView) view.findViewById(R.id.tv_gas_type_90);
        tv_gas_type_90.setText(Html.fromHtml("90<sup>#</sup"));
        tv_gas_type_93 = (TextView) view.findViewById(R.id.tv_gas_type_93);
        tv_gas_type_93.setText(Html.fromHtml("93<sup>#</sup"));
        tv_gas_type_97 = (TextView) view.findViewById(R.id.tv_gas_type_97);
        tv_gas_type_97.setText(Html.fromHtml("97<sup>#</sup"));
        tv_gas_type_0 = (TextView) view.findViewById(R.id.tv_gas_type_0);
        tv_gas_type_0.setText(Html.fromHtml("0<sup>#</sup"));
    }

    private void initData() {
        mList = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("image", images[i]);
            map.put("title", titles[i]);
            map.put("desc", descs[i]);
            mList.add(map);
        }
        mAdapter = new SimpleAdapter(getActivity(), mList, R.layout.find_menu_item,
                new String[]{"image", "title", "desc"}, new int[]{R.id.iv_find_image, R.id.tv_find_title, R.id.tv_find_desc});
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTransaction = manager.beginTransaction();
                switch (position) {
                    case 0:   //跳转车友圈
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout, new CarFriendFragment(), "CarFriend");
                            mTransaction.addToBackStack("CarFriend");
                        } else {
                            Toast.makeText(getActivity(), "当前还未登录", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:     //跳转挪车助手
                        if (PathUtils.havedLogin) {
                            mTransaction.add(R.id.ll_main_layout, new MoveHelperFragment(), "MoveHelper");
                            mTransaction.addToBackStack("MoveHelper");
                        } else {
                            Toast.makeText(getActivity(), "当前还未登录", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2:
                        mTransaction.add(R.id.ll_main_layout, new NewsListFragment(), "NewsList");
                        mTransaction.addToBackStack("NewsList");
                        break;
                }
                mTransaction.commit();
            }
        });

        getGasPrice();
    }

    public void getGasPrice() {  //请求油价
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String gasPrice = "";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(PathUtils.GAS_PRICE).build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String str = response.body().string();
                        gasPrice = str;
                        Log.d(">>>>>Get请求", str);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
                return gasPrice;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("showapi_res_code");
                    if (code == 0) {
                        JSONObject body = jsonObject.getJSONObject("showapi_res_body");
                        int ret_code = body.getInt("ret_code");
                        if (ret_code == 0) {
                            JSONArray array = body.getJSONArray("list");
                            JSONObject o = array.getJSONObject(0);
                            String p90 = o.getString("p90");
                            tv_gas_90_price.setText(p90);
                            String p0 = o.getString("p0");
                            tv_gas_0_price.setText(p0);
                            String p97 = o.getString("p97");
                            tv_gas_97_price.setText(p97);
                            String p93 = o.getString("p93");
                            tv_gas_93_price.setText(p93);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute();


    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
